package com.atguigu.tingshu.account.consumer;


import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/***
 * 监听充值订单超时未支付的消息
 */
@Component
@Log4j2
public class RechargeTimeOutConsumer {

    @Autowired
    private RechargeInfoService rechargeInfoService;

    /**
     * 监听超时充值订单消息,取消超时未支付的充值订单
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "account_recharge_delay_queue")
    public void rechargeTimeOut(Channel channel, Message message){
        //获取消息:用户id
        byte[] body = message.getBody();
        String orderNo = new String(body);
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            //取消充值订单
            rechargeInfoService.cancleRechargeInfo(orderNo);
            //确认消息
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            //判断消息是否第一次,不是就记录日志丢弃
            if(messageProperties.getRedelivered()){
                log.error("超时取消充值订单失败,订单No为:" + orderNo
                        + ",失败的原因为:" + e.getMessage());
                channel.basicReject(deliveryTag, false);
            }else{
                //是第一次,就放回去再来一次
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
